package edu.suda.xsap.controller;

import edu.suda.xsap.dto.MemberBindRecordDto;
import edu.suda.xsap.dto.MemberCardDto;
import edu.suda.xsap.service.MemberBindRecordService;
import edu.suda.xsap.service.MemberCardService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("/bind")
public class MemberBindRecordController {

    private static final Logger log = LoggerFactory.getLogger(MemberBindRecordController.class);
    @Autowired
    private MemberBindRecordService memberBindRecordService;
    @Autowired
    private MemberCardService memberCardService;

    @PostMapping
    public ResponseEntity<Void> bind(@RequestBody MemberBindRecordDto memberBindRecordDto) {
        memberBindRecordService.bind(memberBindRecordDto);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<MemberBindRecordDto> getById(@PathVariable Integer id) {
        MemberBindRecordDto memberBindRecordDto = memberBindRecordService.findById(id);
        return ResponseEntity.ok(memberBindRecordDto);
    }

    @GetMapping("/list")
    public ResponseEntity<List<MemberBindRecordDto>> getAll() {
        List<MemberBindRecordDto> memberBindRecordDtos = memberBindRecordService.findAll();
        return ResponseEntity.ok(memberBindRecordDtos);
    }

    @PutMapping("/update/{id}")
    public ResponseEntity<Void> update(@PathVariable Integer id, @RequestBody MemberBindRecordDto memberBindRecordDto) {
        memberBindRecordDto.setId(id);
        memberBindRecordService.update(memberBindRecordDto);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Void> delete(@PathVariable Integer id) {
        memberBindRecordService.delete(id);
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/member-cards/{memberId}")
    public ResponseEntity<List<MemberCardDto>> getByMemberId(@PathVariable("memberId") Integer memberId) {
        log.info("memberId: {}", memberId);
        // 第一步：获取绑定记录中的 cardId 列表
        List<Integer> cardIds = memberBindRecordService.findCardIdsByMemberId(memberId);
        log.info("cardIds: {}", cardIds);

        // 第二步：使用 cardId 列表查询会员卡详细信息
        List<MemberCardDto> memberCardDtos = memberCardService.findByCardIds(cardIds);
        return ResponseEntity.ok(memberCardDtos);
    }
}
